package com.xmjs.baselibrary.network;

import com.xmjs.baselibrary.utils.SP;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 * 下载任务的订阅器
 */
public abstract class DownLoadSubscriber implements Observer<ResponseBody> {
    private SP sp;
    private String url;
    private String savePath;
    private String fileName;
    private long range;

    public DownLoadSubscriber(SP sp, String url, String savePath, String fileName) {
        this.sp = sp;
        this.url = url;
        this.savePath = savePath;
        this.fileName = fileName;
        range = sp.getLong(url);
    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(ResponseBody responseBody) {
        RandomAccessFile randomAccessFile = null;
        InputStream inputStream = null;
        long total = range;
        long responseLength = 0;
        try {
            byte[] buf = new byte[2048];
            int len = 0;
            responseLength = responseBody.contentLength();
            inputStream = responseBody.byteStream();

            File file = new File(savePath, fileName);
            File dir = new File(savePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            randomAccessFile = new RandomAccessFile(file, "rwd");
            if (range == 0) {
                randomAccessFile.setLength(responseLength);
            }
            randomAccessFile.seek(range);

            int progress = 0;
            int lastProgress = 0;

            while ((len = inputStream.read(buf)) != -1) {
                randomAccessFile.write(buf, 0, len);
                total += len;
                lastProgress = progress;
                progress = (int) (total * 100 / randomAccessFile.length());
                if (progress > 0 && progress != lastProgress) {
                    onProgress(progress);
                }
            }
            onComplete();
        } catch (Exception e) {
            onError(e);
        } finally {
            try {
                sp.putLong(url, total);
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(Throwable t) {

    }

    @Override
    public void onComplete() {

    }

    /**
     * 下载进度
     *
     * @param progress
     */
    public abstract void onProgress(int progress);
}
